/*
	后台页面控制器
*/
'use strict';
var AV 			= require('leanengine');
let admin		= {};

/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
admin.loginPage = function(req,res) {
	var error=req.query.error;
	//console.log("loginPage:"+error);
	if(req.AV.user) return res.redirect('/admin/index');
  res.render('admin-login',{error:error});
}

/**
 * 后台索引页面
 * 2015.04.18  by 胡斌
 */
admin.indexPage = function(req, res) {
	console.log(process.env.Test);

	res.render('admin-index.html',{
		user:req.AV.user
	});
}

/**
 * 后台登录
 * 2015.04.18  by 胡斌
 */
admin.doLogin = function(req,res) {
	//console.log(req.body.email);
	AV.User.logIn(req.body.username,req.body.password).then(function(user) {
			//console.log(user.get("username"));
			res.saveCurrentUser(user);
			//跳转到profile页面。
			res.redirect('/admin/index');
	},function(error) {
		if(typeof(error)=="object"){error=error.message;}
		console.error(error);
		//登录失败，跳转到登录页面
		res.redirect('/admin-login?error='+error);
	});
}

/**
 * 后台登出
 * 2015.04.18  by 胡斌
 */
admin.doLogout = function(req,res) {
	//AV.User.logOut();
	//console.log("doLogout");
	var user = req.currentUser;
	user.logOut();
	res.clearCurrentUser();
  res.redirect('/admin-login');
}

/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
admin.doCkAuth = function(req,res,next) {
	//console.log(req.AV.user);
	if(!req.AV.user){// 判断用户是否已经登录
		res.redirect('/admin-login');
		return false;
	}
	next();
}

/**
 * 初始化系统
 * 2016.06.30  by 胡斌
 */
admin.doSysInit = function(req,res,next) {
	var querySysConfig 	= new AV.Query(avSysConfig);
	querySysConfig.equalTo("name","init-1");
	querySysConfig.count().then(function(count){
		if(count==0){
			var promises = [];

			var	lottery={};
			//注册抽奖
			lottery.register={};
			lottery.register.enabled=true;
			//消费抽奖
			lottery.consumption={};
			lottery.consumption.enabled=true;
			lottery.consumption.money=100;//每消费多少金额送的次数
			//每日抽奖
			lottery.daily={};
			lottery.daily.enabled=true;
			lottery.daily.time=3;//每日可抽次数
			//积分抽奖
			lottery.points={};
			lottery.points.enabled=true;
			var lotterySysConfig=new avSysConfig();
			lotterySysConfig.set("type","common");
			lotterySysConfig.set("name","lottery");
			lotterySysConfig.set("value",lottery);

			promises.push(lotterySysConfig.save());

			//////////
			var newSysConfig=new avSysConfig();
			newSysConfig.set("name","init-1");
			newSysConfig.set("value",true);
			newSysConfig.save();
			promises.push(newSysConfig.save());

			return AV.Promise.when(promises);
		}else{
			return AV.Promise.as(true);
		}
	}).then(function(result){
		if(typeof(result)!="boolean")console.log("Init successed!");
	},function(errors){
		res.json(errors);
		return false;
	});
	next();
}

module.exports = admin;
